package com.fingersoft.util;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Log;

import androidx.annotation.Nullable;

import com.fingersoft.im.utils.AppUtils;
import com.fingersoft.im.utils.JSONUtils;
import com.fingersoft.im.utils.PermissionsUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;

import static android.content.Context.TELEPHONY_SERVICE;
import static com.fingersoft.im.utils.ApplicationUtils.getPackageName;


public final class AppEventUtil {
    private AppEventUtil() {

    }

    private static final String FILE_NAME = "/applog/appEvent.log";
    private static String mRootFilePath = null;

    public static void initRootFilePath(String rootPath) {
        mRootFilePath = rootPath;
        Log.e("Jooper", "______________:" + mRootFilePath);
    }

    private static void writeMsg(String msg) {
        msg += "\n";//添加换行符
        writeException(msg, "/applog", FILE_NAME);
    }

    public static void writeLandingState(AppEventType type) {
        LandingState ls = new LandingState();
        ls.sType = type.getName();
        ls.currentTimeStamp = System.currentTimeMillis();
        ls.userId = AppUtils.getUser().getUserId();
        String msg = JSONUtils.toJsonString(ls);
        writeMsg(msg);
    }

    public static void writeLandingState(int type, String appType, String appId, String appVersion) {
        H5State ls = new H5State();
        if (type == 6) {
            ls.sType = AppEventType.mAppLaunch.getName();
        }
        if (type == 7) {
            ls.sType = AppEventType.mAppClose.getName();
        }
        ls.currentTimeStamp = System.currentTimeMillis();
        ls.userId = AppUtils.getUser().getUserId();
        ls.appType = appType;
        ls.appId = appId;
        if (appVersion != null) {
            ls.versionCode = appVersion;
        }
        String msg = JSONUtils.toJsonString(ls);
        writeMsg(msg);
    }
    @SuppressLint("MissingPermission")
    public static void writeLandingState(AppEventType type, Context context) {
        if (!PermissionsUtils.isGrantedPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, context)) {
            return;
        }
        AppLanch al = new AppLanch();
        al.sType = type.getName();
        al.currentTimeStamp = System.currentTimeMillis();
        al.userId = AppUtils.getUser().getUserId();
        TelephonyManager tm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
        if (tm != null) {
            al.deviceId = tm.getDeviceId();
        }
        al.systemName = "ANDROID"; // 系统名称
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(),
                PackageManager.GET_CONFIGURATIONS);
            al.appVersion = pi.versionName;// app版本号
            al.codeVersion = String.valueOf(pi.versionCode);// 代码版本号
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        al.model = android.os.Build.MODEL;// 设备类型
        al.systemVersion = android.os.Build.VERSION.RELEASE;// 设备系统版本号
        al.name = android.os.Build.BRAND;//设备名称
        String msg = JSONUtils.toJsonString(al);
        writeMsg(msg);
    }

    private static void writeException(String content, String path, String fileName) {
        try {
            File file = new File(mRootFilePath + path);
            if (!file.exists()) {
                //如果文件夹不存在，先创建文件夹 
                file.mkdirs();
            }
            File targetFile = new File(mRootFilePath + fileName);
            // 以指定文件创建RandomAccessFile对象  
            try (RandomAccessFile raf = new RandomAccessFile(targetFile, "rw")) {
                // 将文件记录指针移动到最后  
                raf.seek(targetFile.length());
                // 输出文件内容  
                raf.write(content.getBytes());
            }
            LogUtil.i("appevent:", content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Nullable
    private static String readException()
    {
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                // 获得SD卡对应的存储目录  
                File sdCardDir = Environment.getExternalStorageDirectory();
                // 获取指定文件对应的输入流  
                FileInputStream fis = new FileInputStream(sdCardDir.getCanonicalPath() + FILE_NAME);
                // 将指定输入流包装成BufferReader  
                StringBuilder sb;
                try (BufferedReader br = new BufferedReader(new InputStreamReader(fis))) {
                    sb = new StringBuilder("");
                    String line = null;
                    // 循环读取文件内容  
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                }
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public  static void delete() {
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                // 获取SD卡的目录  
                File sdCardDir = Environment.getExternalStorageDirectory();
                File file = new File(sdCardDir.getCanonicalPath()+"/Android/data/"+getPackageName()+"/cache/applog");
                if (!file.exists()) {
                    //如果文件夹不存在，先创建文件夹 
                    file.mkdirs();
                }
                File targetFile = new File(sdCardDir.getCanonicalPath() + FILE_NAME);
                targetFile.delete();
                LogUtil.i("appevent:","上传并删除");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static  class   LandingState{
        private  String sType;
        private  String userId;
        private  long currentTimeStamp;
        public String getsType() {
            return sType;
        }

        public void setsType(String sType) {
            this.sType = sType;
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public Long getCurrentTimeStamp() {
            return currentTimeStamp;
        }

        public void setCurrentTimeStamp(Long currentTimeStamp) {
            this.currentTimeStamp = currentTimeStamp;
        }
    }
    private static  class   H5State{
        private  String sType;
        private  String userId;
        private  long currentTimeStamp;
        private  String  appType="H5OL";// 轻应用类型,同后台返回的应用type字段
        private  String  appId;
        private  String  versionCode;

        public String getAppType() {
            return appType;
        }

        public void setAppType(String appType) {
            this.appType = appType;
        }

        public String getAppId() {
            return appId;
        }

        public void setAppId(String appId) {
            this.appId = appId;
        }
        public String getsType() {
            return sType;
        }

        public void setsType(String sType) {
            this.sType = sType;
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public Long getCurrentTimeStamp() {
            return currentTimeStamp;
        }

        public void setCurrentTimeStamp(Long currentTimeStamp) {
            this.currentTimeStamp = currentTimeStamp;
        }

        public String getVersionCode() {
            return versionCode;
        }

        public void setVersionCode(String versionCode) {
            this.versionCode = versionCode;
        }
    }
    private  static class AppLanch{
       private String  deviceId;// 设备id
       private String systemName; // 系统名称
       private String appVersion; // app版本号
        private String userId;// 用户id
        private String model;// 设备类型
        private String codeVersion;// 代码版本号
        private long currentTimeStamp;// 当前时间戳
        private String systemVersion;// 设备系统版本号
        private String sType;
        private String name;//设备名称
        public String getDeviceId() {
            return deviceId;
        }

        public void setDeviceId(String deviceId) {
            this.deviceId = deviceId;
        }

        public String getSystemName() {
            return systemName;
        }

        public void setSystemName(String systemName) {
            this.systemName = systemName;
        }

        public String getAppVersion() {
            return appVersion;
        }

        public void setAppVersion(String appVersion) {
            this.appVersion = appVersion;
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getModel() {
            return model;
        }

        public void setModel(String model) {
            this.model = model;
        }

        public String getCodeVersion() {
            return codeVersion;
        }

        public void setCodeVersion(String codeVersion) {
            this.codeVersion = codeVersion;
        }

        public long getCurrentTimeStamp() {
            return currentTimeStamp;
        }

        public void setCurrentTimeStamp(long currentTimeStamp) {
            this.currentTimeStamp = currentTimeStamp;
        }

        public String getSystemVersion() {
            return systemVersion;
        }

        public void setSystemVersion(String systemVersion) {
            this.systemVersion = systemVersion;
        }

        public String getsType() {
            return sType;
        }

        public void setsType(String sType) {
            this.sType = sType;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}




